# gozerbot/thr.py
#
#

""" own threading wrapper """

__copyright__ = 'this file is in the public domain'

import ommbot.generic
import threading
import re
import time

# regular expression to determine thread name
methodre = re.compile('method\s+(\S+)', re.I)
funcre = re.compile('function\s+(\S+)', re.I)

class Botcommand(threading.Thread):

    """ thread for running bot commands """

    def __init__(self, group, target, name, args, kwargs):
        self.ievent = args[1]
        result = []
        for i in args:
            result.append(str(i))
        threading.Thread.__init__(self, None, target, name, args, kwargs)

    def run(self):
        """ run the bot command """
        try:
            threading.Thread.run(self)
            if self.ievent.queues:
                for i in self.ievent.queues:
                    i.put_nowait(None)
        except Exception, ex:
            print ex
            ommbot.generic.handle_exception(self.ievent)
            time.sleep(0.1)

class Thr(threading.Thread):

    """ thread wrapper """

    def __init__(self, group, target, name, args, kwargs):
        result = []
        for i in args:
            result.append(str(i))
        threading.Thread.__init__(self, None, target, name, args, kwargs)

    def run(self):
        """ run the thread """
        try:
            threading.Thread.run(self)
        except Exception, ex:
            ommbot.generic.handle_exception()
            time.sleep(0.1)

def getname(func):
    """ get name of function/method """
    name = ""
    method = re.search(methodre, str(func))
    if method:
        name = method.group(1)
    else: 
        function = re.search(funcre, str(func))
        if function:
            name = function.group(1)
        else:
            name = str(func)
    return name

def start_new_thread(func, arglist, kwargs=None):
    """ start a new thread .. set name to function/method name"""
    if not kwargs:
        kwargs = {}
    try:
        name = getname(func)
        if not name:
            name = 'noname'
        thread = Thr(None, target=func, name=name, args=arglist, \
kwargs=kwargs)
        thread.start()
        return thread
    except:
        ommbot.generic.handle_exception()
        time.sleep(0.1)
        
def start_bot_command(func, arglist, kwargs=None):
    """ start a new thread .. set name to function/method name"""
    if not kwargs:
        kwargs = {}
    try:
        name = getname(func)
        if not name:
            name = 'noname'
        thread = Botcommand(group=None, target=func, name=name, args=arglist, \
kwargs=kwargs)
        thread.start()
        return thread
    except:
        ommbot.generic.handle_exception()
        time.sleep(0.1)
